package controllers

import javax.inject.{Inject, Singleton}

import play.api.libs.json.{Json, _}
import play.api.mvc.{AbstractController, ControllerComponents}
import services.{PlayService, Student}
@Singleton
class PlayController  @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  /**
    * obj  转成json
    * @return
    */
  def selectStudent =Action{
      implicit val studentWrite:Writes[Student]=(
        (JsPath \ "name").write[String] and
          (JsPath \ "age").write[Int] and
          (JsPath \ "tell")
      )(unlift(Student.unapply))

    Ok( Json.toJson(PlayService.selectStudent()))
  }

  /**
    * json 转成obj
    * @return
    */
  def insertStudent = Action(parse.json) { request =>
    val jsonDictionary = request.body.validate[Student]
    jsonDictionary.fold(
      errors => {
        BadRequest(Json.obj("code" -> MyCode.code_1._1, "message" -> JsError.toJson(errors)))
      },
      res => {
        PlayService.insertStudent(res)
        Ok(Json.obj("code" -> MyCode.code_0._1, "message" -> MyCode.code_0._2, "content" -> MyCode.code_3._1))
      }
    )
  }
}
